const glob = require("glob");
const path = require("path");
const fs = require("fs");
const pluginName = "yipackRoutesGenerator";
const pagesDir = path.resolve(__dirname, "..", "src", "pages", "**/meta.json");
const routesFile = path.resolve(__dirname, "..", "src", ".cache", "_routes.js");
let i = 0;
class YipackRoutesGeneratorPlug {
    apply(compiler) {
        compiler.hooks.afterCompile.tap(pluginName, (watching) => {
            // 获取发生变化的文件列表
            glob(pagesDir, {}, (err, files) => {
                files.forEach((file) => {
                    file = path.normalize(file);
                    if (watching.fileDependencies.has(file) === false) {
                        watching.fileDependencies.add(file);
                    }
                });
            });
        });
        compiler.hooks.watchRun.tap(pluginName, (watching) => {
            // 获取发生变化的文件列表

            let bool = false;
            let filename = "";
            for (let prop in watching.watchFileSystem.watcher.mtimes) {
                filename = path.basename(prop);
                if (filename === "meta.json") {
                    bool = true;
                }
            }
            console.log("====================================================");
            console.log(filename);
            console.log(watching.fileDependencies);
            if (bool === true) {
                let routes = [];
                glob(pagesDir, {}, (err, files) => {
                    files.forEach((file) => {
                        let meta = JSON.parse(fs.readFileSync(file, { encoding: "utf8" }));
                        let route = JSON.stringify(meta.route)
                            .replace(/"\/\*/g, "")
                            .replace(/\*\/"/g, "");
                        routes.push(route);
                        let file2 = path.normalize(file);
                        if (watching.fileDependencies.has(file2) === false) {
                            watching.fileDependencies.add(file2);
                        }
                    });
                    fs.writeFileSync(routesFile, "module.exports = [" + routes.join(",") + "]");
                });
            }
        });
    }
}
module.exports = YipackRoutesGeneratorPlug;
